package com.internetCafes.spms.web.certificate.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.common.module.excel.ExcelUtils;
import com.internetCafes.spms.common.module.excel.po.EmployeeInfoExcel;
import com.internetCafes.spms.common.module.excel.po.EmployeeInfoExcelPro;
import com.internetCafes.spms.common.utils.DateUtils;
import com.internetCafes.spms.common.utils.ExcelImportUtil;
import com.internetCafes.spms.common.utils.IdCardUtils;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.core.annotation.SysLog;
import com.internetCafes.spms.core.exception.RRException;
import com.internetCafes.spms.core.model.pageModel.DataGrid;
import com.internetCafes.spms.core.utils.FileUtils;
import com.internetCafes.spms.core.utils.IdWorker;
import com.internetCafes.spms.core.utils.Query;
import com.internetCafes.spms.core.utils.R;
import com.internetCafes.spms.web.certificate.model.vo.CertificateHoldersVO;
import com.internetCafes.spms.web.certificate.entity.EmployeeInfo;
import com.internetCafes.spms.web.certificate.service.CertificateInfoService;
import com.internetCafes.spms.web.certificate.service.EmployeeInfoService;
import com.internetCafes.spms.web.certificate.vo.EmployeeInfoVo;
import com.internetCafes.spms.web.certificate.vo.EntryQuitInfo;
import com.internetCafes.spms.web.customer.common.cont.CommonConst;
import com.internetCafes.spms.web.customer.common.util.UserInfoUtil;
import com.internetCafes.spms.web.customer.entity.role.RoleDeptDataAsso;
import com.internetCafes.spms.web.customer.entity.user.EntUserInfo;
import com.internetCafes.spms.web.customer.model.role.RoleDeptDataDo;
import com.internetCafes.spms.web.customer.service.role.IRoleDeptDataAssoService;
import com.internetCafes.spms.web.customer.service.user.IEntUserInfoService;
import com.internetCafes.spms.web.sys.model.ResourceInfo;
import com.internetCafes.spms.web.sys.model.UserInfo;
import com.internetCafes.spms.web.sys.service.ResourceInfoService;
import com.internetCafes.spms.web.tenant.common.TenantConst;
import com.internetCafes.spms.web.tenant.model.TenantDeptInfo;
import com.internetCafes.spms.web.tenant.model.podo.TenantDeptInfoPlusDo;
import com.internetCafes.spms.web.tenant.model.podo.TenantDeptInfoPlusPo;
import com.internetCafes.spms.web.tenant.service.ITenantDeptInfoPlusService;
import com.internetCafes.spms.web.tenant.service.TenantDeptInfoService;
import com.internetCafes.spms.web.tenant.vo.TenantDeptInfoVo;
import com.sms.common.util.hutool.core.collection.CollectionUtil;
import com.sms.common.util.hutool.core.util.IdcardUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecgframework.poi.excel.entity.ImportSheetParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 员工信息表
 *
 * @author Sunny
 * @email rekeeper2011@hotmail.com
 * @date 2019-10-31 18:10:59
 */
@RestController
@RequestMapping("/certificate/employeeInfo")
public class EmployeeInfoController {

    @Autowired
    private CertificateInfoService certificateInfoService;

    @Autowired
    private EmployeeInfoService employeeInfoService;

    @Autowired
    private ResourceInfoService resourceInfoService;

    @Autowired
    private TenantDeptInfoService tenantDeptInfoService;

    @Autowired
    private IEntUserInfoService userInfoService;

    @Autowired
    private ITenantDeptInfoPlusService tenantDeptInfoPlusService;

    @Autowired
    private IRoleDeptDataAssoService roleDeptDataAssoService;

    @Value("${system.upload.pic}")
    private String picPath;

    @Value("${system.remote.url}")
    private String remoteUrl;

    @Value("${system.upload.others}")
    private String othersPath;

    /**
     * 获取持证人列表
     *
     * @return 持证人列表
     * @author Zj
     */
    @RequestMapping("/holders")
    @RequiresPermissions("certificate:employeeInfo:info")
    public R certificateHolders() {
        List<CertificateHoldersVO> holders = certificateInfoService.certificateHolders();
        return R.ok().put("data", holders);
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, HttpServletRequest request) {

        //查询列表数据
        Query query = new Query(params);
        params = new HashMap<>();
        String tenantId = request.getParameter("tenantId");
        String deptId = request.getParameter("deptId");
        String status = request.getParameter("status");
        String name = request.getParameter("name");
        String idCard = request.getParameter("idCard");
        String mobile = request.getParameter("mobile");
        String maxAge = request.getParameter("maxAge");
        String minAge = request.getParameter("minAge");
        String gender = request.getParameter("gender");
        String academic = request.getParameter("academic");
        String jobGrade = request.getParameter("jobGrade");
        String entryTime = request.getParameter("entryTime");
        String contractExpirationTime = request.getParameter("contractExpirationTime");
        String post = request.getParameter("post");
        String orderBy = request.getParameter("orderBy");
        String inOrder = request.getParameter("inOrder");
        String nameOrPost = request.getParameter("nameOrPost");
        String onCompanyFlag = request.getParameter("onCompanyFlag");
        String roleId = request.getParameter("roleId");
        String roleName = request.getParameter("roleName");
        String id = request.getParameter("id");

        // 添加接口是否进行数据过滤标签 20220526 修改接口过滤操作为接口通过标签进行配置，默认为过滤
        String filterFlagStr = request.getParameter("filterFlag");
        Integer filterFlag = 1;
        if (StringUtils.isNotBlank(filterFlagStr)) {
            filterFlag = Integer.parseInt(filterFlagStr);
        }

        if (StringUtils.isNotBlank(id)) {
            params.put("id", Long.parseLong(id));
        }

        if (StringUtils.isNotBlank(tenantId)) {
            params.put("tenantId", Long.parseLong(tenantId));
        }

        if (StringUtils.isNotBlank(onCompanyFlag)) {
            params.put("onCompanyFlag", Integer.parseInt(onCompanyFlag));
        }

        if (StringUtils.isNotBlank(deptId)) {
            List<TenantDeptInfoVo> depts = new ArrayList<>();
            depts = tenantDeptInfoService.getChildren(Long.valueOf(deptId), depts);
            if (CollectionUtil.isEmpty(depts)) {
                params.put("deptId", deptId);
            } else {
                List<Long> deptIds = new ArrayList<>();
                deptIds.add(Long.valueOf(deptId));
                for (TenantDeptInfoVo tenantDeptInfoVo : depts) {
                    deptIds.add(tenantDeptInfoVo.getId());
                }
                params.put("deptIds", deptIds);
            }
        }

        if (StringUtils.isNotBlank(nameOrPost)) {
            params.put("nameOrPost", nameOrPost);
        }

        if (StringUtils.isNotBlank(status)) {
            params.put("status", Integer.parseInt(status));
        }

        if (StringUtils.isNotBlank(maxAge)) {
            params.put("maxAge", Integer.parseInt(maxAge));
        }

        if (StringUtils.isNotBlank(minAge)) {
            params.put("minAge", Integer.parseInt(minAge));
        }

        if (StringUtils.isNotBlank(gender)) {
            params.put("gender", Integer.parseInt(gender));
        }

        if (StringUtils.isNotBlank(name)) {
            params.put("name", name);
        }

        if (StringUtils.isNotBlank(idCard)) {
            params.put("idCard", idCard);
        }

        if (StringUtils.isNotBlank(mobile)) {
            params.put("mobile", mobile);
        }

        if (StringUtils.isNotBlank(academic)) {
            params.put("academic", academic);
        }

        if (StringUtils.isNotBlank(roleId)) {
            params.put("roleId", roleId);
        }

        if (StringUtils.isNotBlank(roleName)) {
            params.put("roleName", roleName);
        }

        if (StringUtils.isNotBlank(jobGrade)) {
            params.put("jobGrade", jobGrade);
        }

        if (StringUtils.isNotBlank(post)) {
            params.put("post", post);
        }

        if (StringUtils.isNotBlank(entryTime)) {
            params.put("entryTime", DateUtils.strToDate(entryTime));
        }

        if (StringUtils.isNotBlank(contractExpirationTime)) {
            params.put("contractExpirationTime", DateUtils.strToDate(contractExpirationTime));
        }

        if (StringUtils.isNotBlank(orderBy) && StringUtils.isNotBlank(inOrder)) {
            if (orderBy.equals("academic")) {
                if (inOrder.equals("asc")) {
                    params.put("orderBy", "FIELD(academic,'博士','硕士','本科','专科','高职高专','中专','高中','初中','小学','其他')");
                    params.put("inOrder", "");
                } else {
                    params.put("orderBy", "FIELD(academic,'其他','小学','初中','高中','中专','高职高专','专科','本科','硕士','博士')");
                    params.put("inOrder", "");
                }
            } else {
                params.put("orderBy", com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(orderBy));
                params.put("inOrder", inOrder);
            }
        }
        UserInfo userEntity = ShiroUtils.getUserEntity();
        if (!UserInfoUtil.entSuperAdminJudge(userEntity)
                && !TenantConst.TENANT_DEPT_ROOT_PARENT_ID.equals(userEntity.getTenantDeptId())
                && CommonConst.FlagEnum.IS.getId().equals(filterFlag)) {
            // 提供默认值
            List<Long> deptIdList = new ArrayList<>();
            deptIdList.add(-1L);
            List<Long> deptPoIdList
                    = tenantDeptInfoPlusService.deptList(new TenantDeptInfoPlusDo().setAncestorId(userEntity.getTenantDeptId()))
                    .stream().map(TenantDeptInfoPlusPo::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(deptPoIdList)) {
                deptIdList.addAll(deptPoIdList);
            }
            List<Long> assoDeptIdList = roleDeptDataAssoService.listPo(new RoleDeptDataDo().setUserId(userEntity.getId()))
                    .stream().map(RoleDeptDataAsso::getDeptId)
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(assoDeptIdList)) {
                deptIdList.addAll(assoDeptIdList);
            }
            params.put("deptIdList", deptIdList);
        }

        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        DataGrid dataGrid = employeeInfoService.dataGrid(params, query.getPage(), query.getLimit());

        return R.ok().put("page", dataGrid);
    }


    /**
     * 列表
     */
    @RequestMapping("/getEmployeeInfos")
    // @RequiresPermissions("certificate:employeeInfo:info")
    public List<EmployeeInfo> getEmployeeInfos(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        String tenantId = request.getParameter("tenantId");
        String deptId = request.getParameter("deptId");

        if (StringUtils.isNotBlank(tenantId)) {
            params.put("tenantId", Long.parseLong(tenantId));
        }

        if (StringUtils.isNotBlank(deptId)) {
            if (Integer.parseInt(deptId) != 0) {
                params.put("deptId", deptId);
            }
        }
        params.put("status", CommonConstants.CommonStatus.ENABLE);
        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        params.put("types", new Integer[]{
                CommonConstants.EmployeeInfoType.TENANT_ADMIN,
                CommonConstants.EmployeeInfoType.TENANT_CONTANT,
                CommonConstants.EmployeeInfoType.TENANT_Employee});

        return employeeInfoService.query(params);
    }

    /**
     * 根据ID获取数据
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("certificate:employeeInfo:info")
    public R info(@PathVariable("id") Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<EmployeeInfoVo> employeeInfoVoList = employeeInfoService.selectByParamsUnionDept(params);
        EmployeeInfoVo vo = null;
        if (CollectionUtils.isNotEmpty(employeeInfoVoList)) {
            vo = employeeInfoVoList.get(0);
            Map<String, Object> _params = new HashMap<>();
            _params.put("moduleId", vo.getId());
            _params.put("moduleCode", CommonConstants.ResourceInfo_PIC_EmployeeInfo);
            List<ResourceInfo> resourceInfoList = resourceInfoService.query(_params);
            if (CollectionUtils.isNotEmpty(resourceInfoList)) {
                vo.setContractInfoList(resourceInfoList);
            }
        }
        return R.ok().put("e", vo).put("remoteUrl", remoteUrl + File.separator + "pic/");
    }


    /**
     * 保存
     */
    @SysLog("保存员工信息")
    @RequestMapping("/save")
    @RequiresPermissions("certificate:employeeInfo:save")
    public R save(@RequestBody EmployeeInfoVo employeeInfo) {
        if (ShiroUtils.getUserId() != CommonConstants.SUPER_ADMIN) {
            employeeInfo.setTenantId(ShiroUtils.getUserEntity().getDeptId());
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("idCard", employeeInfo.getIdCard());
        List<EmployeeInfo> query = employeeInfoService.query(params);
        if (CollectionUtil.isNotEmpty(query)) {
            return R.error("该员工已存在");
        }
        EmployeeInfo _e = new EmployeeInfo();
        BeanUtils.copyProperties(employeeInfo, _e);
        _e.setStatus(CommonConstants.CommonStatus.ENABLE);
        _e.setType(CommonConstants.EmployeeInfoType.TENANT_Employee);
        _e.setCreateTime(new Date());
        _e.setEmployeeFlag(CommonConstants.CommonStatus.ENABLE);
        employeeInfoService.save(_e);
        saveResourceInfo(ShiroUtils.getUserEntity(), employeeInfo, _e);
        return R.ok();
    }

    /**
     * 保存
     */
    @SysLog("批量导入员工信息")
    @RequestMapping("/batchSave")
    @RequiresPermissions("certificate:employeeInfo:save")
    public R batchSave(MultipartFile file) {
        List<R> resultList = new ArrayList<>();
        Integer countFail = 0;
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        IdWorker id = new IdWorker(2);
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File videoFilePath = new File(othersPath);
        if (!videoFilePath.exists()) {
            videoFilePath.mkdirs();
        }
        List<EmployeeInfoExcel> dealInfoExcelList = null;
        if (fileType.toUpperCase().endsWith("XLS") || fileType.toUpperCase().endsWith("XLSX")) {
            String filePath = othersPath + File.separator + id.nextId() + fileType;

            try {
                file.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }

            Map<String, ImportSheetParams> sheetClassParamsMap = new HashMap<>();
            Map<String, Object> excel2Map;
            sheetClassParamsMap.put("Sheet1", new ImportSheetParams("employeeInfoExcel", 1, 1, new String[]{"学历", "姓名", "性别", "身份证", "手机号码", "部门名称", "职位", "员工状态", "入职时间", "合同到期日期", "离职时间", "是否缴纳社保", "参保日期", "技术负责人", "负责内容", "专业", "毕业时间", "婚姻状况", "备注", "企业名称"}, EmployeeInfoExcel.class));
            try {
                excel2Map = ExcelImportUtil.importExcel2Map(new File(filePath), sheetClassParamsMap, null);
            } catch (Exception e) {
                return R.error(e.getMessage());
            }
            dealInfoExcelList = (List<EmployeeInfoExcel>) excel2Map.get("Sheet1");
            for (EmployeeInfoExcel employeeInfoExcel : dealInfoExcelList) {
                EmployeeInfoVo employeeInfoVo = new EmployeeInfoVo();
                BeanUtils.copyProperties(employeeInfoExcel, employeeInfoVo);
                if (ShiroUtils.getUserId() != CommonConstants.SUPER_ADMIN) {
                    employeeInfoVo.setTenantId(ShiroUtils.getUserEntity().getDeptId());
                }
                Map<String, Object> params = new HashMap<>();
                params.put("deptName", employeeInfoExcel.getDeptName());
                List<TenantDeptInfo> tenantDeptInfos = tenantDeptInfoService.query(params);
                if (tenantDeptInfos.size() == 0) {
                    R error = R.error("未找到对应部门");
                    error.put("name", employeeInfoExcel.getName());
                    error.put("idCard", employeeInfoExcel.getIdCard());
                    resultList.add(error);
                    countFail++;
                    continue;
                }
                if (!IdcardUtil.isValidCard(employeeInfoExcel.getIdCard())) {
                    R error = R.error("身份证号有误");
                    error.put("name", employeeInfoExcel.getName());
                    error.put("idCard", employeeInfoExcel.getIdCard());
                    resultList.add(error);
                    countFail++;
                    continue;
                }
                employeeInfoVo.setDeptId(tenantDeptInfos.get(0).getId());
                employeeInfoVo.setStatus(CommonConstants.CommonStatus.ENABLE);
                employeeInfoVo.setType(CommonConstants.EmployeeInfoType.TENANT_Employee);
                employeeInfoVo.setEmployeeFlag(CommonConstants.CommonStatus.ENABLE);
                employeeInfoVo.setCreateTime(new Date());
                employeeInfoService.save(employeeInfoVo);
            }
        }
        R ok = R.ok();
        ok.put("data", resultList)
                .put("success", dealInfoExcelList.size() - countFail)
                .put("fail", countFail);
        return ok;
    }


    /**
     * 修改
     */
    @SysLog("修改员工信息")
    @RequestMapping("/update")
    @RequiresPermissions("certificate:employeeInfo:update")
    public R update(@RequestBody EmployeeInfoVo employeeInfo) {
        EmployeeInfo e = employeeInfoService.findById(employeeInfo.getId());
        if (e != null) {
            EmployeeInfo _e = new EmployeeInfo();
            BeanUtils.copyProperties(employeeInfo, _e);
            _e.setTenantId(e.getTenantId());
            // _e.setCreateTime(e.getCreateTime());
            _e.setType(e.getType());
            _e.setUpdateTime(new Date());
            _e.setStatus(e.getStatus());
            employeeInfoService.updateEntire(_e);
            saveResourceInfo(ShiroUtils.getUserEntity(), employeeInfo, _e);
        }
        return R.ok();
    }


    /**
     * 保存资源信息
     *
     * @param u
     * @param vo
     * @param c
     */
    private void saveResourceInfo(UserInfo u, EmployeeInfoVo vo, EmployeeInfo c) {
        Map<String, Object> params;
        if (StringUtils.isNotBlank(vo.getConstractPic()) && vo.getConstractPic().split(",").length > 0) {
            params = new HashMap<>();
            params.put("moduleCode", CommonConstants.ResourceInfo_PIC_EmployeeInfo);
            params.put("moduleId", c.getId());
            resourceInfoService.deleteByModuleAndUserId(params);
            String[] certiPics = vo.getConstractPic().split(",");
            for (String certiPic : certiPics) {
                ResourceInfo r = new ResourceInfo(u.getId(), CommonConstants.ResourceInfo_PIC_EmployeeInfo, c.getId(), "pic" + File.separator + certiPic);
                resourceInfoService.save(r);
            }
        }
    }


    /**
     * 删除
     */
    @SysLog("删除员工信息")
    @PostMapping("/delete/{id}")
    @RequiresPermissions("certificate:employeeInfo:delete")
    public R delete(@PathVariable("id") Long id) {

        // 判断有无证书
        Map<String, Object> params = new HashMap<>();
        params.put("employeeId", id);
        params.put("statuses", new Integer[]{CommonConstants.CertificateStatus.BID_USED, CommonConstants.CertificateStatus.NO_USE, CommonConstants.CertificateStatus.BORROW_OUT, CommonConstants.CertificateStatus.PROJECT_USED, CommonConstants.CertificateStatus.BID_SUCCESS, CommonConstants.CertificateStatus.OTHER_STATUS, CommonConstants.CertificateStatus.BORROW_IN_RETURN, CommonConstants.CertificateStatus.BORROW_IN});
        long count = certificateInfoService.count(params);
        if (count > 0) {
            return R.error("请先删除该员工相关证书");
        }

        LambdaQueryWrapper<EntUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EntUserInfo::getUserId, id);
        int employeeAccountAmount = userInfoService.count(queryWrapper);

        if (employeeAccountAmount > BigDecimal.ROUND_UP){
            return R.error("存在子账号，无法删除！");
        }
        EmployeeInfo e = employeeInfoService.findById(id);
        e.setStatus(CommonConstants.CommonStatus.DISABLE);
        employeeInfoService.update(e);
        return R.ok();
    }


    /**
     * 还原
     */
    @RequestMapping("/recover")
    @RequiresPermissions("certificate:employeeInfo:delete")
    public R recover(@RequestBody Long[] ids) {
        if (ids.length > 0) {
            EmployeeInfo e;
            for (Long id : ids) {
                e = employeeInfoService.findById(id);
                if (e != null) {
                    e.setStatus(CommonConstants.CommonStatus.ENABLE);
                    employeeInfoService.update(e);
                }
            }
        }
        return R.ok();
    }


    /**
     * 上传
     */
    @RequestMapping("/upload")
    @RequiresPermissions("certificate:employeeInfo:save")
    public R upload(MultipartFile file) {

        if (file.isEmpty()) {
            return R.error("上传文件不能为空");
        }

        IdWorker id = new IdWorker(2);
        String fileName = id.nextId() + "";
        try {
            fileName = FileUtils.transform(file, picPath, fileName, 2, "M", new String[]{FileUtils.JPG, FileUtils.PNG});
        } catch (Exception e) {
            return R.error(e.getMessage());
        }

        return R.ok().put("fileName", fileName).put("remoteUrl", remoteUrl + File.separator + "pic/");
    }

    /**
     * 批量导出
     */
    @RequestMapping("/export")
    @RequiresPermissions("certificate:employeeInfo:list")
    public void export(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> params = new HashMap<>();
        String id = request.getParameter("id");
        String tenantId = request.getParameter("tenantId");
        String deptId = request.getParameter("deptId");
        String name = request.getParameter("name");
        String idCard = request.getParameter("idCard");
        String mobile = request.getParameter("mobile");
        String tenantName = request.getParameter("tenantName");
        String deptName = request.getParameter("deptName");
        String academic = request.getParameter("academic");
        String onCompanyFlag = request.getParameter("onCompanyFlag");
        String status = request.getParameter("status");
        String post = request.getParameter("post");
        String orderBy = request.getParameter("orderBy");
        String inOrder = request.getParameter("inOrder");

        if (StringUtils.isNotBlank(id)) {
            params.put("id", Long.parseLong(id));
        }

        if (StringUtils.isNotBlank(tenantId)) {
            params.put("tenantId", Long.parseLong(tenantId));
        }

        if (StringUtils.isNotBlank(deptId)) {
            params.put("deptId", Long.parseLong(deptId));
        }

        if (StringUtils.isNotBlank(name)) {
            params.put("name", name);
        }

        if (StringUtils.isNotBlank(idCard)) {
            params.put("idCard", idCard);
        }

        if (StringUtils.isNotBlank(mobile)) {
            params.put("mobile", mobile);
        }

        if (StringUtils.isNotBlank(tenantName)) {
            params.put("tenantName", tenantName);
        }

        if (StringUtils.isNotBlank(deptName)) {
            params.put("deptName", deptName);
        }

        if (StringUtils.isNotBlank(academic)) {
            params.put("academic", academic);
        }

        if (StringUtils.isNotBlank(onCompanyFlag)) {
            params.put("onCompanyFlag", Integer.parseInt(onCompanyFlag));
        }

        if (StringUtils.isNotBlank(onCompanyFlag)) {
            params.put("onCompanyFlag", Integer.parseInt(onCompanyFlag));
        }

        if (StringUtils.isNotBlank(status)) {
            params.put("status", DateUtils.strToDate(status));
        }

        if (StringUtils.isNotBlank(post)) {
            params.put("post", post);
        }

        if (StringUtils.isNotBlank(orderBy) && StringUtils.isNotBlank(inOrder)) {
            if (orderBy.equals("academic")) {
                if (inOrder.equals("asc")) {
                    params.put("orderBy", "FIELD(academic,'博士','硕士','本科','专科','高职高专','中专','高中','初中','小学','其他')");
                    params.put("inOrder", "");
                } else {
                    params.put("orderBy", "FIELD(academic,'其他','小学','初中','高中','中专','高职高专','专科','本科','硕士','博士')");
                    params.put("inOrder", "");
                }
            } else {
                params.put("orderBy", com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(orderBy));
                params.put("inOrder", inOrder);
            }
        }
        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        if (!params.containsKey("status")) {
            params.put("status", 1);
        }

        List<EmployeeInfoVo> employeeInfoVos = employeeInfoService.selectByParamsUnionDept(params);
        try {
            if (employeeInfoVos != null && employeeInfoVos.size() > 0) {
                List<EmployeeInfoExcelPro> orderInfoExcelList = new ArrayList<>();
                EmployeeInfoExcelPro o;
                for (EmployeeInfoVo vo : employeeInfoVos) {
                    o = new EmployeeInfoExcelPro();
                    BeanUtils.copyProperties(vo, o);
                    orderInfoExcelList.add(o);
                }
                ExcelUtils.exportExcel(orderInfoExcelList, "人员信息统计", "人员信息统计", EmployeeInfoExcelPro.class, "人员信息统计.xls", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取各年龄段员工数量
     */
    @GetMapping("/ageCount")
    @RequiresPermissions("certificate:employeeInfo:list")
    public R countAge() {
        Map<String, Object> params = new HashMap<>();
        params.put("status", CommonConstants.CommonStatus.ENABLE);
        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        List<EmployeeInfo> query = employeeInfoService.query(params);
        Integer young = 0;
        Integer adult = 0;
        Integer middle = 0;
        Integer old = 0;
        for (EmployeeInfo employeeInfo : query) {
            if (employeeInfo.getIdCard() == null || "".equals(employeeInfo.getIdCard())) {
                continue;
            }
            Integer age = IdCardUtils.getPersonAgeFromIdCard(employeeInfo.getIdCard());
            if (age < 20) {
                young++;
                continue;
            }
            if (age <= 30) {
                adult++;
                continue;
            }
            if (age <= 40) {
                middle++;
                continue;
            }
            old++;
        }
        int total = young + adult + middle + old;
        return R.ok()
                .put("young", young)
                .put("youngPercent", total > 0 ? String.format("%.3f", (double) young / total) : 0)
                .put("adult", adult)
                .put("adultPercent", total > 0 ? String.format("%.3f", (double) adult / total) : 0)
                .put("middle", middle)
                .put("middlePercent", total > 0 ? String.format("%.3f", (double) middle / total) : 0)
                .put("old", old)
                .put("oldPercent", total > 0 ? String.format("%.3f", (double) old / total) : 0);
    }

    /**
     * 根据性别获取员工数量
     */
    @GetMapping("/sexCount")
    @RequiresPermissions("certificate:employeeInfo:list")
    public R countSex() {
        Map<String, Object> params = new HashMap<>();
        params.put("status", CommonConstants.CommonStatus.ENABLE);
        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        List<EmployeeInfo> query = employeeInfoService.query(params);
        long male = 0L;
        long female = 0L;
        for (EmployeeInfo employeeInfo : query) {
            if (employeeInfo.getGender() == null) {
                continue;
            }
            if (employeeInfo.getGender() == CommonConstants.Gender.MALE) {
                male++;
            } else if (employeeInfo.getGender() == CommonConstants.Gender.FEMALE) {
                female++;
            }
        }
        return R.ok().put("male", male).put("malePercent", (male + female) != 0 ? String.format("%.3f", (double) male / (male + female)) : "0")
                .put("female", female).put("femalePercent", (male + female) != 0 ? String.format("%.3f", (double) female / (male + female)) : "0");
    }

    /**
     * 当月员工入职离职情况
     */
    @GetMapping("/changeCount")
    @RequiresPermissions("certificate:employeeInfo:list")
    public R countChange() {
        EmployeeInfo employeeInfo = new EmployeeInfo();
        employeeInfo.setEntryTime(new Date());
        employeeInfo.setCompanyEndTime(new Date());
        EntryQuitInfo entryQuitInfo = employeeInfoService.countByMonth(employeeInfo);
        return R.ok().put("entry", entryQuitInfo.getEntry()).put("quit", entryQuitInfo.getQuit());
    }

    /**
     * 员工学历情况
     */
    @GetMapping("/academicCount")
    @RequiresPermissions("certificate:employeeInfo:list")
    public R countAcademic() {
        Map<String, Object> params = new HashMap<>();
        params.put("status", CommonConstants.CommonStatus.ENABLE);
        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        List<String> academics = new ArrayList<>();
        academics.add("博士");
        academics.add("硕士");
        academics.add("本科");
        params.put("academics", academics);
        Long high = employeeInfoService.count(params);
        academics = new ArrayList<>();
        academics.add("专科");
        academics.add("高职高专");
        params.put("academics", academics);
        Long mid = employeeInfoService.count(params);
        academics = new ArrayList<>();
        academics.add("中专");
        params.put("academics", academics);
        Long normal = employeeInfoService.count(params);
        academics = new ArrayList<>();
        params.put("academics", academics);
        Long total = employeeInfoService.count(params);
        long low = total - high - mid - normal;
        return R.ok().put("high", high).put("highPercent", String.format("%.3f", (double) high / total))
                .put("mid", mid).put("midPercent", String.format("%.3f", (double) mid / total))
                .put("normal", normal).put("normalPercent", String.format("%.3f", (double) normal / total))
                .put("low", low).put("lowPercent", String.format("%.3f", (double) low / total));
    }

    /**
     * 三年内员工入职离职统计
     */
    @GetMapping("/ThreeYearsEntryQuitCount")
    @RequiresPermissions("certificate:employeeInfo:list")
    public R countThreeYearsEntryQuit() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -36);
        List<EntryQuitInfo> list = new ArrayList<>();
        EmployeeInfo employeeInfo;
        EntryQuitInfo entryQuitInfo;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        for (int i = 0; i < 36; i++) {
            employeeInfo = new EmployeeInfo();
            employeeInfo.setEntryTime(calendar.getTime());
            employeeInfo.setCompanyEndTime(calendar.getTime());
            entryQuitInfo = employeeInfoService.countByMonth(employeeInfo);
            entryQuitInfo.setDate(sdf.format(calendar.getTime()));
            list.add(entryQuitInfo);
            calendar.add(Calendar.MONTH, 1);
        }
        return R.ok().put("data", list);
    }

    @PostMapping("/listWithCertiCount")
    @RequiresPermissions("certificate:employeeInfo:list")
    public R CertiCountlist(@RequestBody Map<String, Object> params) {
        Query query = new Query(params);
        params.put("page", query.getPage());
        params.put("rows", query.getLimit());
        List<EmployeeInfoVo> employeeInfoVos = employeeInfoService.selectByParamsUnionCertificate(params);
        return R.ok().put("data", employeeInfoVos);
    }

    @PostMapping("/onCompanyTimeCount")
    @RequiresPermissions("certificate:employeeInfo:list")
    public R countOnCompanyTime() {
        Map<String, Object> params = new HashMap<>();
        params.put("status", CommonConstants.CommonStatus.ENABLE);
        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        List<EmployeeInfoVo> employeeInfoVoList = employeeInfoService.selectByJobParams(params);
        int firstClassOnCompany = 0;
        int firstClassLeaveCompany = 0;
        int secondClassOnCompany = 0;
        int secondClassLeaveCompany = 0;
        int thirdClassOnCompany = 0;
        int thirdClassLeaveCompany = 0;
        int fourthClassOnCompany = 0;
        int fourthClassLeaveCompany = 0;
        for (EmployeeInfoVo employeeInfoVo : employeeInfoVoList) {
            if (employeeInfoVo.getOnCompanyTime() < 365) {
                if (employeeInfoVo.getOnCompanyFlag() == CommonConstants.CommonStatus.ENABLE) {
                    firstClassOnCompany++;
                    continue;
                }
                if (employeeInfoVo.getOnCompanyFlag() == CommonConstants.CommonStatus.DISABLE) {
                    firstClassLeaveCompany++;
                    continue;
                }
            }
            if (employeeInfoVo.getOnCompanyTime() < 365 * 3) {
                if (employeeInfoVo.getOnCompanyFlag() == CommonConstants.CommonStatus.ENABLE) {
                    secondClassOnCompany++;
                    continue;
                }
                if (employeeInfoVo.getOnCompanyFlag() == CommonConstants.CommonStatus.DISABLE) {
                    secondClassLeaveCompany++;
                    continue;
                }
            }
            if (employeeInfoVo.getOnCompanyTime() < 365 * 5) {
                if (employeeInfoVo.getOnCompanyFlag() == null || employeeInfoVo.getOnCompanyFlag() == CommonConstants.CommonStatus.ENABLE) {
                    thirdClassOnCompany++;
                    continue;
                }
                if (employeeInfoVo.getOnCompanyFlag() == CommonConstants.CommonStatus.DISABLE) {
                    thirdClassLeaveCompany++;
                    continue;
                }
            }
            if (employeeInfoVo.getOnCompanyTime() > 365 * 5) {
                if (employeeInfoVo.getOnCompanyFlag() == null || employeeInfoVo.getOnCompanyFlag() == CommonConstants.CommonStatus.ENABLE) {
                    fourthClassOnCompany++;
                    continue;
                }
                if (employeeInfoVo.getOnCompanyFlag() == CommonConstants.CommonStatus.DISABLE) {
                    fourthClassLeaveCompany++;
                }
            }
        }
        return R.ok().put("firstClassOnCompany", firstClassOnCompany).put("firstClassLeaveCompany", firstClassLeaveCompany)
                .put("secondClassOnCompany", secondClassOnCompany).put("secondClassLeaveCompany", secondClassLeaveCompany)
                .put("thirdClassOnCompany", thirdClassOnCompany).put("thirdClassLeaveCompany", thirdClassLeaveCompany)
                .put("fourthClassOnCompany", fourthClassOnCompany).put("fourthClassLeaveCompany", fourthClassLeaveCompany);
    }

    /**
     * 员工在职离职统计
     */
    @GetMapping("/jobCount")
    @RequiresPermissions("certificate:employeeInfo:list")
    public R countJob() {
        Map<String, Object> params = new HashMap<>();
        params.put("status", CommonConstants.CommonStatus.ENABLE);
        params.put("employeeFlag", CommonConstants.CommonStatus.ENABLE);
        Long total = employeeInfoService.count(params);
        params.put("onCompanyFlag", CommonConstants.CommonStatus.DISABLE);
        Long quitJob = employeeInfoService.count(params);
        return R.ok().put("onJob", total - quitJob).put("quitJob", quitJob);
    }
}
